import Vue from 'vue'
import getDeviceInfo from '../common/deviceInfo'
Vue.directive('inputDelete', {
    inserted: function (el, bind) {
        if (getDeviceInfo().isIOS) {
            el.addEventListener('keydown', (e) => {
                if (e.keyCode === 8) {
                    e.preventDefault()
                    let text = el.value
                    if (text.length) {
                        const start = el.selectionStart
                        const end = el.selectionEnd
                        const length = text.length
                        if (end === length) {
                            if (start !== end) {
                                text = text.slice(0, start)
                            } else {
                                text = text.slice(0, start - 1)
                            }
                        } else {
                            if (end === 0) {
                                return
                            }
                            let p1
                            let p2
                            if (start !== end) {
                                if (start === 0) {
                                    text = text.slice(end)
                                    Vue.prototype.$nextTick(() => {
                                        el.setSelectionRange(0, 0)
                                    })
                                } else {
                                    p1 = text.slice(0, start)
                                    p2 = text.slice(end)
                                    text = p1 + p2
                                    Vue.prototype.$nextTick(() => {
                                        el.setSelectionRange(start, start)
                                    })
                                }
                            } else {
                                p1 = text.slice(0, start - 1)
                                p2 = text.slice(end)
                                text = p1 + p2
                                Vue.prototype.$nextTick(() => {
                                    el.setSelectionRange(start - 1, start - 1)
                                })
                            }
                        }
                    }
                    el.value = text
                    bind.value.target[bind.value.name] = text
                }
            })
        }
    }
})